﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using BLL.Installer;
using BLL.Interface.User;
using BLL.Model.User;
using System.Data;
using BLL.DbAccess;
using BLL.Utility;
using Castle.Core.Logging;

namespace BLL.Implement.User
{
    public class RoleInfoImpl : IRoleInfo
    {
        public ILogger Logger { get; set; }
        private readonly DefaultContext _defaultContext;
        private readonly DbSet<RoleInfo> _roleInfoContext;

        public RoleInfoImpl()
        {
            _defaultContext = ContainerHelper.Instance.Container.Resolve<DefaultContext>();
            _roleInfoContext = _defaultContext.RoleInfoContext;
        }

        public bool AddRoleInfo(RoleInfo roleInfo)
        {
            _roleInfoContext.Add(roleInfo);
            _defaultContext.SaveChanges();
            Logger.InfoFormat("新增了一条记录：{0}", roleInfo);
            return true;
        }

        public bool UpdateRoleInfo(RoleInfo roleInfo)
        {
            _defaultContext.Entry(roleInfo).State = EntityState.Modified;
            _defaultContext.SaveChanges();
            Logger.InfoFormat("更新了一条记录：{0}", roleInfo);
            return true;
        }

        public bool DeleteRoleInfoById(int id)
        {
            var roleInfo = FindRoleInfoById(id, true);
            if (roleInfo == null)
            {
                Logger.FatalFormat("删除失败：没有找到编号为{0}的记录", id);
                return false;
            }
            _roleInfoContext.Remove(roleInfo);
            _defaultContext.SaveChanges();
            Logger.InfoFormat("删除了一条记录：{0}", roleInfo);
            return true;
        }

        public bool DeleteAllRoleInfo()
        {
            const string sql = "delete from RoleInfo";
            try
            {
                _defaultContext.Database.ExecuteSqlCommand(sql);
                return true;
            }
            catch (Exception e)
            {
                Logger.FatalFormat("删除所有记录失败，SQL：{0}，错误{1}", sql, e.Message);
                return false;
            }
        }

        public IList<RoleInfo> GetAllRoleInfo()
        {
            return _roleInfoContext.AsNoTracking().ToList();
        }

        public RoleInfo FindRoleInfoById(int id, bool tracking)
        {
            return tracking
                       ? _roleInfoContext.AsNoTracking().FirstOrDefault(p => p.Id == id)
                       : _roleInfoContext.Find(id);
        }

        public IList<RoleInfo> GetRoleInfoByFilter(dynamic condition, Tuple<string, string> sort, PageInfo page)
        {
            var query = _roleInfoContext.AsNoTracking().AsQueryable();

            if (sort == null || string.IsNullOrWhiteSpace(sort.Item1) || string.IsNullOrWhiteSpace(sort.Item2))
            {
                sort = new Tuple<string, string>("Id", "asc");
            }

            if (page != null)
            {
                page.TotalRecords = query.Count();
                return query.OrderBy(sort.Item1, sort.Item2)
                                            .Skip(page.PageSize * (page.CurrentPage - 1))
                                            .Take(page.PageSize).ToList();
            }
            return query.ToList();
        }

        public RoleInfo FindRoleInfoByName(string name)
        {
            return _roleInfoContext.AsNoTracking().FirstOrDefault(p => p.Name == name);
        }

        public bool AddRoleInfo(IList<RoleInfo> roleInfoList)
        {
            try
            {
                foreach (var entry in roleInfoList)
                {
                    _roleInfoContext.Add(entry);
                }
                int count = _defaultContext.SaveChanges();
                Logger.InfoFormat("{0}条记录被插入。", count);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return false;
            }
        }

        public bool DeleteRoleInfoById(IList<int> roleInfoList)
        {
            try
            {
                foreach (int id in roleInfoList)
                {
                    var entryToDelete = FindRoleInfoById(id, true);
                    _roleInfoContext.Remove(entryToDelete);
                }
                int count = _defaultContext.SaveChanges();
                Logger.InfoFormat("{0}条记录被删除。", count);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return false;
            }
        }

    }

}
